import { defineStore } from 'pinia'

import { getLocal, setLocal, removeLocal } from '@/utils/localStorage'
import { getUserInfo } from '@/views/login/store'
import { toast } from '@/utils/common'

import { logout } from '@/views/login/store'

const useUserStore = defineStore('user', {
    state: () => {
        return {
            token: getLocal('token') || '',
            userInfo: getLocal('userInfo') || {}
        }
    },
    actions: {
        // 设置token
        setToken(token: string) {
            this.token = token
            setLocal('token', token)
        },
        async getUserInfo(token: string) {
            const res: any = await getUserInfo(token)
            if (res.status === 200) {
                this.setUserInfo(res.result.userInfo)
            } else {
                toast('error', '', res.result.msg)
                logout()
                this.clearUserInfo()
                throw new Error(res.result.msg)
            }
        },
        // 设置用户信息
        setUserInfo(userInfo: any) {
            this.userInfo = userInfo
            setLocal('userInfo', userInfo)
        },
        // 清除用户信息
        clearUserInfo() {
            this.token = ''
            this.userInfo = {}
            removeLocal(['token', 'userInfo'])
        }
    }
})

export default useUserStore
